<template>
  <div class="vue-admin-beautiful-wrapper" :class="classObj">
    <div
      v-if="'horizontal' === layout"
      class="layout-container-horizontal"
      :class="{
        fixed: header === 'fixed',
        'no-tabs-bar': tabsBar === 'false' || tabsBar === false,
      }"
    >
      <div :class="header === 'fixed' ? 'fixed-header' : ''">
        <vab-top-bar />
        <div
          v-if="tabsBar === 'true' || tabsBar === true"
          :class="{ 'tag-view-show': tabsBar }"
        >
          <div class="vab-main">
            <vab-tabs-bar />
          </div>
        </div>
      </div>
      <div class="vab-main main-padding">
        <vab-ad />
        <vab-app-main />
      </div>
    </div>
    <div
      v-else
      class="layout-container-vertical"
      :class="{
        fixed: header === 'fixed',
        'no-tabs-bar': tabsBar === 'false' || tabsBar === false,
      }"
    >
      <div
        v-if="device === 'mobile' && collapse === false"
        class="mask"
        @click="handleFoldSideBar"
      ></div>
      <vab-side-bar />
      <div class="vab-main" :class="collapse ? 'is-collapse-main' : ''">
        <div :class="header === 'fixed' ? 'fixed-header' : ''">
          <vab-nav-bar />
          <vab-tabs-bar v-if="tabsBar === 'true' || tabsBar === true" />
        </div>
        <vab-ad />
        <div class="table-container" style="width: 95%; margin: 0 auto">
          <vab-query-form>
            <vab-query-form-left-panel>
              <el-button icon="el-icon-plus" type="primary" @click="handleAdd">
                添加新订单
              </el-button>
              <el-button
                icon="el-icon-delete"
                type="danger"
                :disabled="selectRows.length === 0"
                @click="handleDelete"
              >
                删除订单
              </el-button>
            </vab-query-form-left-panel>
          </vab-query-form>
          <el-table
            ref="tableSort"
            v-loading="listLoading"
            :data="orderList"
            :height="500"
            :element-loading-text="elementLoadingText"
            @selection-change="setSelectRows"
          >
            <el-table-column
              show-overflow-tooltip
              type="selection"
              width="55"
            ></el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="orderId"
              label="订单ID"
            ></el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="status"
              label="状态"
              sortable
            >
              <template #default="{ row }">
                <el-tooltip
                  :content="row.status"
                  class="item"
                  effect="dark"
                  placement="top-start"
                >
                  <el-tag :type="row.status | statusFilter">
                    {{ row.status }}
                  </el-tag>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              label="产品ID"
              prop="productId"
            ></el-table-column>
            <el-table-column
              show-overflow-tooltip
              label="产品件数"
              prop="productNum"
            ></el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="deadline"
              label="截止日期"
              sortable
            ></el-table-column>
            <el-table-column show-overflow-tooltip label="操作" width="280px">
              <template #default="{ row }">
                <el-button
                  type="success"
                  :disabled="row.status === '未开始'"
                  @click="handleGantt(row)"
                >
                  查看甘特图
                </el-button>
                <el-button
                  type="primary"
                  :disabled="row.status !== '未开始'"
                  @click="handleEdit(row)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  :disabled="row.status !== '未开始'"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <br />
          <h3>
            候选订单
            <el-tooltip
              class="item"
              effect="dark"
              content="添加或修改的订单，但是未在当前排程中计算"
              placement="right"
            >
              <i class="el-icon-info"></i>
            </el-tooltip>
          </h3>
          <el-table
            ref="tableSort"
            v-loading="listLoading"
            :data="newOrderList"
            :element-loading-text="elementLoadingText"
            @selection-change="setSelectRows"
          >
            <el-table-column
              show-overflow-tooltip
              type="selection"
              width="55"
            ></el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="orderId"
              label="订单ID"
            ></el-table-column>
            <el-table-column
              show-overflow-tooltip
              label="产品ID"
              prop="productId"
            ></el-table-column>
            <el-table-column
              show-overflow-tooltip
              label="产品件数"
              prop="productNum"
            ></el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="deadline"
              label="截止日期"
              sortable
            ></el-table-column>
            <el-table-column show-overflow-tooltip label="操作" width="280px">
              <template #default="{ row }">
                <el-button type="primary" @click="handleEdit(row)">
                  编辑
                </el-button>
                <el-button type="danger" @click="handleDelete(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <table-edit ref="edit"></table-edit>
          <gantt-table ref="gantt"></gantt-table>
        </div>
        <vab-app-main />
      </div>
    </div>
    <el-backtop />
  </div>
</template>

<script>
  import { mapActions, mapGetters } from 'vuex'
  import { tokenName } from '@/config'
  import TableEdit from './components/TableEdit'
  import { getAllOrders, getNewOrders } from '../../api/order/getAllOrders'
  import { getCookie } from '../../utils/cookie'
  import { deleteOrder } from '../../api/order/deleteOrder'
  import GanttTable from './components/GanttTable'
  export default {
    name: 'OrderManagement',
    components: {
      GanttTable,
      TableEdit,
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          已完成: 'success',
          正在作业: 'gray',
          已延期: 'danger',
          未开始: 'warning',
        }
        return statusMap[status]
      },
    },
    data() {
      return {
        imgShow: true,
        orderList: [
          {
            orderId: 1,
            productId: 11,
            productNum: 111,
            deadline: '2020-07-01',
            status: '开始',
          },
        ],
        newOrderList: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        background: true,
        selectRows: '',
        elementLoadingText: '正在加载...',
      }
    },
    computed: {
      ...mapGetters({
        layout: 'settings/layout',
        tabsBar: 'settings/tabsBar',
        collapse: 'settings/collapse',
        header: 'settings/header',
        device: 'settings/device',
      }),
      classObj() {
        return {
          mobile: this.device === 'mobile',
        }
      },
      height() {
        return this.$baseTableHeight()
      },
    },
    created() {
      this.fetchData0()
    },
    beforeMount() {
      window.addEventListener('resize', this.handleResize)
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.handleResize)
    },
    mounted() {
      this.oldLayout = this.layout
      const userAgent = navigator.userAgent
      if (userAgent.includes('Juejin')) {
        this.$baseAlert(
          'vue-admin-beautiful不支持在掘金内置浏览器演示，请手动复制以下地址到浏览器中查看http://mpfhrd48.sanxing.uz7.cn/vue-admin-beautiful'
        )
      }
      const isMobile = this.handleIsMobile()
      if (isMobile) {
        if (isMobile) {
          //横向布局时如果是手机端访问那么改成纵向版
          this.$store.dispatch('settings/changeLayout', 'vertical')
        } else {
          this.$store.dispatch('settings/changeLayout', this.oldLayout)
        }
        this.$store.dispatch('settings/toggleDevice', 'mobile')
        setTimeout(() => {
          this.$store.dispatch('settings/foldSideBar')
        }, 2000)
      } else {
        this.$store.dispatch('settings/openSideBar')
      }
      this.$nextTick(() => {
        window.addEventListener(
          'storage',
          (e) => {
            if (e.key === tokenName || e.key === null) window.location.reload()
            if (e.key === tokenName && e.value === null)
              window.location.reload()
          },
          false
        )
      })
    },
    methods: {
      ...mapActions({
        handleFoldSideBar: 'settings/foldSideBar',
      }),
      handleIsMobile() {
        return document.body.getBoundingClientRect().width - 1 < 992
      },
      handleResize() {
        if (!document.hidden) {
          const isMobile = this.handleIsMobile()
          if (isMobile) {
            //横向布局时如果是手机端访问那么改成纵向版
            this.$store.dispatch('settings/changeLayout', 'vertical')
          } else {
            this.$store.dispatch('settings/changeLayout', this.oldLayout)
          }

          this.$store.dispatch(
            'settings/toggleDevice',
            isMobile ? 'mobile' : 'desktop'
          )
        }
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleAdd() {
        this.$refs['edit'].showEdit()
      },
      handleEdit(row) {
        this.$refs['edit'].showEdit(row)
      },
      handleDelete(row) {
        if (row.orderId) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            deleteOrder({ ids: row.orderId }).then(() => {
              this.$baseMessage('删除成功！', 'success')
              this.fetchData0()
            })
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.orderId).join()
            this.$baseConfirm(
              '你确定要删除选中的' + this.selectRows.length + '项吗',
              null,
              async () => {
                deleteOrder({ ids: ids }).then(() => {
                  this.$baseMessage('删除成功！', 'success')
                  this.fetchData0()
                })
              }
            )
          } else {
            this.$baseMessage('未选中任何行', 'error')
            return false
          }
        }
      },
      handleGantt(row) {
        this.$refs['gantt'].showGantt(row.orderId)
      },
      async fetchData0() {
        this.listLoading = true
        this.orderList = await this.getOrderList()
        this.newOrderList = await this.getNewOrderList()
        setTimeout(() => {
          this.listLoading = false
        }, 500)
      },
      async getOrderList() {
        getAllOrders(getCookie('cur_date')).then((res) => {
          this.orderList = res
          for (let i = 0; i < this.orderList.length; i++) {
            switch (this.orderList[i].status) {
              case 0:
                this.orderList[i].status = '未开始'
                break
              case 1:
                this.orderList[i].status = '正在作业'
                break
              case 2:
                this.orderList[i].status = '已完成'
                break
              default:
                this.orderList[i].status = '已延期'
            }
          }
          this.total = this.orderList.length
        })
      },
      async getNewOrderList() {
        getNewOrders(getCookie('cur_date')).then((res) => {
          this.newOrderList = res
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  @mixin fix-header {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    z-index: $base-z-index - 2;
    width: 100%;
    overflow: hidden;
  }

  .vue-admin-beautiful-wrapper {
    position: relative;
    width: 100%;
    height: 100%;

    .layout-container-horizontal {
      position: relative;

      &.fixed {
        padding-top: calc(#{$base-top-bar-height} + #{$base-tabs-bar-height});
      }

      &.fixed.no-tabs-bar {
        padding-top: $base-top-bar-height;
      }

      ::v-deep {
        .vab-main {
          width: 88%;
          margin: auto;
        }

        .fixed-header {
          @include fix-header;
        }

        .tag-view-show {
          background: $base-color-white;
          box-shadow: $base-box-shadow;
        }

        .nav-bar-container {
          .fold-unfold {
            display: none;
          }
        }

        .main-padding {
          .app-main-container {
            margin-top: $base-padding;
            margin-bottom: $base-padding;
            background: $base-color-white;
          }
        }
      }
    }

    .layout-container-vertical {
      position: relative;

      .mask {
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: $base-z-index - 1;
        width: 100%;
        height: 100vh;
        overflow: hidden;
        background: #000;
        opacity: 0.5;
      }

      &.fixed {
        padding-top: calc(#{$base-nav-bar-height} + #{$base-tabs-bar-height});
      }

      &.fixed.no-tabs-bar {
        padding-top: $base-nav-bar-height;
      }

      .vab-main {
        position: relative;
        min-height: 100%;
        margin-left: $base-left-menu-width;
        background: #f6f8f9;
        transition: $base-transition;

        ::v-deep {
          .fixed-header {
            @include fix-header;

            left: $base-left-menu-width;
            width: $base-right-content-width;
            box-shadow: $base-box-shadow;
            transition: $base-transition;
          }

          .nav-bar-container {
            position: relative;
            box-sizing: border-box;
          }

          .tabs-bar-container {
            box-sizing: border-box;
          }

          .app-main-container {
            width: calc(100% - #{$base-padding} - #{$base-padding});
            margin: $base-padding auto;
            background: $base-color-white;
            border-radius: $base-border-radius;
          }
        }

        &.is-collapse-main {
          margin-left: $base-left-menu-width-min;

          ::v-deep {
            .fixed-header {
              left: $base-left-menu-width-min;
              width: calc(100% - 65px);
            }
          }
        }
      }
    }

    /* 手机端开始 */
    &.mobile {
      ::v-deep {
        .el-pager,
        .el-pagination__jump {
          display: none;
        }

        .layout-container-vertical {
          .el-scrollbar.side-bar-container.is-collapse {
            width: 0;
          }

          .vab-main {
            width: 100%;
            margin-left: 0;
          }
        }

        .vab-main {
          .fixed-header {
            left: 0 !important;
            width: 100% !important;
          }
        }
      }
    }

    /* 手机端结束 */
  }
</style>
